from django.http import JsonResponse
from app.aoduo_admin.models import AdminAccount, AdminGroup, AuthType


def check_admin_login(func):
    """
    检查管理员用户是否登录
    :param func:
    :return:
    """

    def wrapper(self, request, *args, **kwargs):
        if request.session.get('admin') is not None:
            return func(self, request, *args, **kwargs)
        else:
            return JsonResponse({
                'status': False,
                'errMsg': '管理员账户还未登录'
            }, status=401)

    return wrapper


def getAdminUser(email):
    """
    通过获取request的session中email来获取管理员用户对象
    :param email:
    :return:
    """
    return AdminAccount.objects.get(email=email)


def adminAuthCheck(admin, authID):
    """
    管理员权限检查
    :param admin:
    :param authID:
    :return:
    """
    if admin.admin_type == '1':
        # 总管理员
        return True
    if admin.admin_type == '2':
        # 副管理员
        return True
    adminGroup = AdminGroup.objects.filter(group_admin=admin)
    auth = AuthType.objects.get(id=authID)
    flag = False
    for group in adminGroup:
        if auth in group.auth.all():
            flag = True
            break
    if flag:
        return True
    else:
        return False
